<template lang='pug'>
.drawUntil(ref='drawHelp')
    .header()
        .toolbar_btn(@click="test") 测试
        .toolbar_btn(@click="setPtType(PtType.Dot)" :class="ptType==PtType.Dot?'active':''") 点
        .toolbar_btn(@click="setPtType(PtType.Ployline)" :class="ptType==PtType.Ployline?'active':''") 线
        .toolbar_btn(@click="setPtType(PtType.Ploygon)" :class="ptType==PtType.Ploygon?'active':''") 面
        .toolbar_btn
            input(type='checkbox' value='编辑' v-model='enEdit') 
            span 编辑
        .toolbar_btn(@click='savejson') 保存
        .toolbar_btn(@click='loadjson') 加载
    .content(v-if="ptType==PtType.Dot")
        template(v-for="itm,idx in points")
            .mark_row
                .mark_dot {{idx+1}}
                .mark_icons
                    .iconbtn 
                        i.el-icon-edit(@click='flyTo(idx)')
                    .iconbtn
                        i.el-icon-position(@click="flyTo(idx,'dot')")
                    .iconbtn
                        i.el-icon-delete(@click="del(idx,'dot')")
            .mark_xyz
                input(v-model="dots[itm].llh.lon")
                input(v-model="dots[itm].llh.lat")
                input(v-model="dots[itm].llh.hei")
    .content(v-else-if="ptType==PtType.Ployline")
        .mark_row(v-for="itm,idx in ploylines")
            .mark_dot {{idx+1}}
            .mark_icons
                .iconbtn 
                    i.el-icon-edit(@click='flyTo(idx)')
                .iconbtn
                    i.el-icon-position(@click="flyTo(idx,'line')")
                .iconbtn
                    i.el-icon-delete(@click="del(idx,'line')")
    .content(v-else-if="ptType==PtType.Ploygon")
        .mark_row(v-for="itm,idx in ploygons")
            .mark_dot {{idx+1}}
            .mark_icons
                .iconbtn 
                    i.el-icon-edit(@click='flyTo(idx)')
                .iconbtn
                    i.el-icon-position(@click="flyTo(idx,'ploygon')")
                .iconbtn
                    i.el-icon-delete(@click="del(idx,'ploygon')")
</template>
<script>
import { eventBus } from "../eventBus";
let Cesium = require('cesium/Cesium');
import {coord} from '../utils/coord'
var DrawMode={ //
    None:0,
    Modify:2,
    Create:1
}
var PtType={
    None:0,
    Dot:1,
    Ployline:2,
    Ploygon:3
}
export default {
    name: 'pop1',
    data() {
        return {
            viewer:null,
            Cesium:null,
            drawMode:DrawMode.None,
            ptType:PtType.Ployline,
            enEdit:false,
            dots:[{nam:11,llh:{lon:110,lat:34.003,hei:0}},
            {nam:11,llh:{lon:110.0009,lat:34.103,hei:0}},
            {nam:11,llh:{lon:110.0003,lat:34.203,hei:0}},
            {nam:11,llh:{lon:110.005,lat:34.03,hei:0}},
            {nam:11,llh:{lon:110,lat:34.003,hei:0}},
            {nam:112,llh:{lon:110.01,lat:34.002,hei:0}},
            {nam:113,llh:{lon:110.02,lat:34.001,hei:0}},
            {nam:114,llh:{lon:110.03,lat:34.004,hei:0}},
            {nam:115,llh:{lon:110.04,lat:34.006,hei:0}},
            {nam:116,llh:{lon:110.05,lat:34.009,hei:0}}],
            ploylines:[[0,1,2]],
            ploygons:[[3,4,5]],
            points:[6,7,8,9],
            marks:[],
            PtType:PtType,
            gp_dh_point:new Cesium.CustomDataSource("drawhelp_dots"),
            gp_dh_line:new Cesium.CustomDataSource("drawhelp_ploylines"),
            gp_dh_ploygon:new Cesium.CustomDataSource("drawhelp_ploygons"),
            hid:0,
        }
    },
    computed:{
        
    },
    watch: {
        dots: {
            handler(){
                this.updatePoints()
            },
            deep: true,
            immediate:true
        },
        ploylines:{
            handler(){
                this.updatePloylines()
            },
            deep:true,
            immediate:true
        },
        ploygons:{
            handler(){
                this.updatePloygons()
            },
            deep:true,
            immediate:true
        }
    },
    mounted () {
        let t=this
        t.$nextTick(()=>{
            t.viewer=t.$parent.viewer
            t.Cesium=t.$parent.Cesium
            t.load()
            t.loadGeo()
            t.viewer.clock.onTick.addEventListener(function(clock) {

            })
        })

    },
    methods:{

        flyTo(idx,type){
            if(type=='dot'){
                this.viewer.zoomTo(this.gp_dh_point.entities.values[this.points[idx]])
            }
            if(type=='line'){
                this.viewer.zoomTo(this.gp_dh_line.entities.values[idx])
            }
            if(type=='ploygon'){
                this.viewer.zoomTo(this.gp_dh_ploygon.entities.values[idx])
            }
        },
        del(idx,type){
            if(type=='dot'){
                this.points.splice(idx,1)
            }
            if(type=='line'){
                this.ploylines.splice(idx,1)
            }
            if(type=='ploygon'){
                this.ploygons.splice(idx,1)
            }
        },
        getType(rs){
            if(rs.point.length>0)return 'dot'
            if(rs.line.length>0)return 'line'
            if(rs.ploygon.length>0)return 'ploygon'
            return 'none'
        },
        searchDot(val){
            let point=this.searchArr(this.points,val)
            let line=this.searchArr2(this.ploylines,val)
            let ploygon=this.searchArr2(this.ploygons,val)
            return {point,line,ploygon}
        },
        searchArr(arr,val){
            let rs=[]
            if(arr.indexOf(val)>-1){
                rs.push({row:arr.indexOf(val)})
            }
            return rs
        },
        searchArr2(arr2,val){
            let rs=[]
            for(let i=0;i<arr2.length;i++){
                if(arr2[i].indexOf(val)>-1){
                    rs.push({row:i,col:arr2[i].indexOf(val)})
                }
            }
            return rs
        },
        savejson(){},
        loadjson(){},
        test(){
            // this.updatePloylines()
            // this.updatePloygons()
            
        },
        updatePoints(){
            let t=this
            let {Cesium,viewer} =this   
            if(Cesium==undefined || viewer==undefined)return
            let ndot=this.gp_dh_point.entities.values.length
            if(ndot>this.dots.length){
                for(let i=ndot;i>this.dots.length;i--){
                    this.gp_dh_point.entities.remove(this.gp_dh_point.entities[i-1])
                }
            }
            if(ndot<this.dots.length){
                for(let i=ndot;i<this.dots.length;i++){
                    let dotOpt={
                        inf:t.dots[i],
                        type:'dh_dot',
                        hid:i,
                        nam:'dh_dot',
                        position: new Cesium.CallbackProperty(()=>{
                                let llh=t.dots[i].llh
                                return Cesium.Cartesian3.fromDegrees(llh.lon,llh.lat,llh.hei)
                            },false),
                        point:{
                            pixelSize:8,
                            color:Cesium.Color.RED,
                            outlineColor:Cesium.Color.YELLOW,
                            outlineWidth:1
                        }
                    }
                    t.gp_dh_point.entities.add(dotOpt)
                }
            }
        },
        updatePloylines(){
            let t=this
            let {Cesium,viewer} =this   
            if(Cesium==undefined || viewer==undefined)return
            let nline=this.gp_dh_line.entities.values.length
            if(nline>this.ploylines.length){
                for(let i=nline;i>this.ploylines.length;i--){
                    this.gp_dh_line.entities.remove(this.gp_dh_line.entities._entities._array[i-1])
                }
            }
            if(nline<this.ploylines.length){
                for(let i=nline;i<this.ploylines.length;i++){
                    let lineOpt={
                        type:'dh_line',
                        nam:'dh_line',
                        polyline : {
                            show : true,
                            positions : new Cesium.CallbackProperty(()=>{
                                return t.getPnts(i)
                            },false),
                            material : Cesium.Color.RED,
                            width : 1
                        }
                    }
                    this.gp_dh_line.entities.add(lineOpt)
                }
            }
        },
        updatePloygons(){
            let t=this
            let {Cesium,viewer} =this   
            if(Cesium==undefined || viewer==undefined)return
            let nline=this.gp_dh_ploygon.entities.values.length
            if(nline>this.ploygons.length){
                for(let i=nline;i>this.ploygons.length;i--){
                    this.gp_dh_ploygon.entities.remove(this.gp_dh_ploygon.entities._entities._array[i-1])
                }
            }
            if(nline<this.ploygons.length){
                for(let i=nline;i<this.ploygons.length;i++){
                    let lineOpt={
                        type:'dh_ploygon',
                        nam:'dh_ploygon',
                        polygon:{
                            hierarchy:new Cesium.CallbackProperty(()=>{
                                return t.getHierarchyPnts(i)
                            },false),
                            height: 0,
                            outline: true,
                            outlineWidth: 10,
                            material: Cesium.Color.RED.withAlpha(0.5)
                        } 
                    }
                    this.gp_dh_ploygon.entities.add(lineOpt)
                }
            }
        },
        getHierarchyPnts(arrIdx){
            let arr=[]
            if(this.ploygons[arrIdx].length<3){
                return Cesium.Cartesian3.fromDegreesArray([0,0, 0.0,0.00000001, 0.00000001,0.00000001,])
            }
            for(let i=0;i<this.ploygons[arrIdx].length;i++){
                let inf=this.dots[this.ploygons[arrIdx][i]]
                let llh=inf.llh
                arr.push(llh.lon,llh.lat)
            }
            return  Cesium.Cartesian3.fromDegreesArray(arr)
        },
        getPnts(arrIdx){
            let arr=[]
            for(let i=0;i<this.ploylines[arrIdx].length;i++){
                let inf=this.dots[this.ploylines[arrIdx][i]]
                let llh=inf.llh
                arr.push(new Cesium.Cartesian3.fromDegrees(llh.lon,llh.lat,llh.hei))
            }
            return arr
        },
        setPtType(type){//设置打点类型
            this.ptType=type==this.ptType?PtType.None:type
        },
        showItm(itm){
            return typeof(itm)=='object'?itm.nam:itm
        },
        loadGeo(){
            this.updatePoints()
            this.updatePloylines()
            this.updatePloygons()
        },
        load() {
            let t=this
            let {viewer,Cesium}=this
            viewer.dataSources.add(t.gp_dh_point)
            viewer.dataSources.add(t.gp_dh_line)
            viewer.dataSources.add(t.gp_dh_ploygon)
            let {scene} =this.viewer
            var ellipsoid = Cesium.Ellipsoid.WGS84;
            let handle=new Cesium.ScreenSpaceEventHandler(scene.canvas)
            let mouseObj=null
            handle.setInputAction(function(e){
                let pick2=scene.camera.pickEllipsoid(e.position, ellipsoid)
                let llh=coord.Cartesian2llh(viewer,pick2)
                if(t.drawMode==DrawMode.Modify){
                    t.drawMode=DrawMode.None
                }else if(t.ptType!=PtType.None){
                    t.dots.push({nam:11,llh})
                    if(t.drawMode==DrawMode.None){//根据状态判定加载
                        t.drawMode=DrawMode.Create
                        if(t.ptType==PtType.Ployline){
                            t.ploylines.push([])
                        }else if(t.ptType==PtType.Ploygon){
                            t.ploygons.push([])
                        }
                    }
                    if(t.ptType==PtType.Dot){
                        t.points.push(t.dots.length-1)
                    }else if(t.ptType==PtType.Ployline){
                        t.ploylines[t.ploylines.length-1].push(t.dots.length-1)
                    }else if(t.ptType==PtType.Ploygon){
                        t.ploygons[t.ploygons.length-1].push(t.dots.length-1)
                    }
                }
                
            }, Cesium.ScreenSpaceEventType.LEFT_CLICK)
            handle.setInputAction(function(e){
                if(t.drawMode==DrawMode.Create){
                    t.drawMode=DrawMode.None
                }
            }, Cesium.ScreenSpaceEventType.RIGHT_CLICK)
            handle.setInputAction(function (movement) {
                if(t.drawMode==DrawMode.Create){
                    let pick=scene.camera.pickEllipsoid(movement.endPosition, ellipsoid)
                    let llh=coord.Cartesian2llh(viewer,pick)
                    t.dots[t.dots.length-1].llh=llh
                }else if(t.drawMode==DrawMode.Modify){
                    let pick=scene.camera.pickEllipsoid(movement.endPosition, ellipsoid)
                    let llh=coord.Cartesian2llh(viewer,pick)
                    t.dots[t.hid].llh=llh
                }else if(t.drawMode==DrawMode.None){
                    var pick = scene.pick(movement.endPosition);
                    if(pick && pick.id && pick.id._type&&pick.id._type=='dh_dot'){//默认应该只捕捉点
                        let search=t.searchDot(pick.id._hid)
                        let type=t.getType(search)
                        if(mouseObj==pick){//还是当前的模型,不进行任何操作
                            eventBus.$emit('tooltip',{pos:movement.endPosition,type,hid:pick.id._hid})//如果是点
                        }else{//新模型或者空模型
                            if(pick.id._type=='dh_dot'){//移动新模型上
                                // pick.id._point._color._value=Cesium.Color.WHITE
                                mouseObj=pick
                                highlight(true)
                                eventBus.$emit('tooltip',{pos:movement.endPosition,type,hid:pick.id._hid})//如果是点}
                            }
                        }
                    }else{//处理异常
                        if(mouseObj!=null){
                            highlight(false)
                        }
                        mouseObj=null
                        eventBus.$emit('tooltip',{pos:movement.endPosition,type:'none'})//如果是点
                    }
                }
            }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
            function highlight(bool=true){
                if(mouseObj.id._type=='dh_dot'){
                    mouseObj.id._point._pixelSize._value=bool?9:6
                }   
            }
            eventBus.$on('tipEvent',(e)=>{
                if(['move','add','del'].indexOf(e.msg)>-1){
                    t.drawMode=DrawMode.Modify
                    t.hid=e.hid
                    eventBus.$emit('tooltip',{type:'none'})//如果是点
                }
            })
        },
        
    }

}
</script>
<style lang="scss" scoped>
.drawUntil{
    z-index: 999;
    position:absolute;
    width: 300px;
    height: 100%;
    background: rgba($color: gray, $alpha:0.5);
    color: white;
    .header{
        display: flex;
        height: 30px;
        .toolbar_btn{
            margin-right: 3px;
            min-width: 28px;
            height: 28px;
            line-height: 28px;
            text-align: center;
            border: 2px solid gray;
            background: rgba($color: gray, $alpha:0.9);
        }
        .toolbar_btn:hover{
            border-color: rgba($color: rgb(50, 187, 250), $alpha:0.8);
        }
    }
    .content{
        display: flex;
        flex-direction: column;
        .mark_row{
            display: flex;
            justify-content: space-between;
            .mark_icons{
                display: flex;
                line-height: 30px;
            }
        }
    }
}
.iconbtn{
    width: 22px;
    height: 22px;
    padding: 2px;
    border: 1px solid gray;
    background: rgba($color: gray, $alpha: 0.3);
}
.active{
    background: rgba($color: rgb(238, 238, 238), $alpha:0.8);
    color: red;
}
</style>